using System.Collections;
using System.Collections.Generic;

namespace Kopernikus.Collections.ThreadSafe
{
    public class ThreadSafeList<T> : IList<T>
    {
        private readonly object SyncRoot = new object();

        private List<T> m_list = new List<T>();

        #region IList<T> Members

        public int IndexOf(T item)
        {
            return m_list.IndexOf(item);
        }

        public void Insert(int index, T item)
        {
            lock (SyncRoot)
            {
                List<T> newList = CopyList();
                newList.Insert(index, item);
                SwitchList(newList);
            }
        }

        public void RemoveAt(int index)
        {
            lock (SyncRoot)
            {
                List<T> newList = CopyList();
                newList.RemoveAt(index);
                SwitchList(newList);
            }
        }

        public T this[int index]
        {
            get { return m_list[index]; }
            set
            {
                lock (SyncRoot)
                {
                    List<T> newList = CopyList();
                    newList[index] = value;
                    SwitchList(newList);
                }
            }
        }

        public void Add(T item)
        {
            lock (SyncRoot)
            {
                List<T> newList = CopyList();
                newList.Add(item);
                SwitchList(newList);
            }
        }

        public void Clear()
        {
            lock (SyncRoot)
            {
                SwitchList(new List<T>());
            }
        }

        public bool Contains(T item)
        {
            return m_list.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            m_list.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return m_list.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(T item)
        {
            bool result;
            lock (SyncRoot)
            {
                List<T> newList = CopyList();
                result = newList.Remove(item);
                SwitchList(newList);
            }
            return result;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return m_list.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return m_list.GetEnumerator();
        }

        #endregion

        private List<T> CopyList()
        {
            return new List<T>(m_list);
        }

        private void SwitchList(List<T> list)
        {
            m_list = list;
        }
    }
}